package com.th.admin.controller.common;

import cn.hutool.core.io.IoUtil;
import com.aliyuncs.CommonResponse;
import com.th.common.core.domain.AjaxResult;
import com.th.system.domain.SysFile;
import com.th.system.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author tuhang
 * @PackageName nswcy-crowdsource-client-server
 * @Package com.th.controller
 * @Date 2023/6/8 18:34
 * @Version 1.0
 */
@RestController
@Slf4j
@Api(tags = "文件处理接口")
public class SysFileController {


    @Resource
    private SysFileService fileService;
    @PostMapping("/api/file/upload")
    @ApiOperation("上传文件")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        fileService.deleteFile(file.getName());
        return AjaxResult.success(fileService.createFile(file.getName(), IoUtil.readBytes(file.getInputStream())));
    }




    @DeleteMapping("/api/file/delete")
    @ApiOperation("删除文件")
    public AjaxResult deleteFile(@RequestParam("id") String id) {
        fileService.deleteFile(id);
        return AjaxResult.success(true);
    }

    @GetMapping("/file/get/{path}")
    @ApiOperation("下载文件")
    public void getFile(HttpServletResponse response, @PathVariable("path") String path) throws IOException {
        SysFile file = fileService.getFile(path);
        if (file == null) {
            log.warn("[getFile][path({}) 文件不存在]", path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        // 设置 header 和 contentType
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(path, "UTF-8"));
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 输出附件
        IoUtil.write(response.getOutputStream(), false, file.getContent());
    }
}
